<template>
  <div class="highlight-search-result">
    <slot name="prefix">
      <span v-if="prefixLabel" class="prefix-label">{{ prefixLabel }}</span>
    </slot>
    <span v-for="(str, index) in result" :key="index">
      <span
        >{{ str
        }}<span class="teld-theme-color" :class="customClass">{{
          matches[index]
        }}</span>
      </span>
    </span>
  </div>
</template>

<script>
import { splitByMatches } from '../../hooks';

/**
 * 搜索功能中高亮显示匹配到的内容
 */
export default {
  name: 'HighlightSearchResult',
  props: {
    /**要展示的原文字内容*/
    source: {
      type: String,
    },
    /**要匹配的关键字*/
    keyword: {
      type: String,
    },
    /**高亮文字的自定义样式类*/
    customClass: {
      type: String | Array,
    },
    /**标题文字*/
    prefixLabel: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      result: [],
      matches: [],
    };
  },
  created() {
    const { result, matches } = splitByMatches(this.source, this.keyword) || {};
    this.result = result || [];
    this.matches = matches || [];
  },
};
</script>

<style></style>
